package mdoc.tp1;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import domain.Address;
import domain.Contact;
import domain.ContactGroup;
import domain.EmailValidator;
import domain.Entreprise;
import domain.PhoneNumber;
import domain.DAO.DAOContact;
import domain.DAO.DAOContactGroup;
import domain.DAO.DAOFactory;
import domain.interfaces.IDAOContact;
import domain.interfaces.IDAOContactGroup;
import domain.interfaces.IDAOEntreprise;

/**
 * Servlet implementation class newContact
 */
public class AddContact extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddContact() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		ServletContext ctx = getServletContext();
		IDAOContactGroup DAOCG = DAOFactory.getDAOContactGroup(ctx);
		ctx.setAttribute("ContactGroups", DAOCG.findAll());
		response.sendRedirect("addContact.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String fn = request.getParameter("firstname");
		String ln = request.getParameter("lastname");
		String em = request.getParameter("email");
		String st = request.getParameter("street");
		String city = request.getParameter("city");
		String zip = request.getParameter("zip");
		String count = request.getParameter("country");
		String mob = request.getParameter("tel_mobile");
		String home = request.getParameter("tel_home");
		String work = request.getParameter("tel_work");
		String nsiret = request.getParameter("numsiret");
		Enumeration e = request.getParameterNames();

		Set<Long> contactgroups = new HashSet<Long>();
		while (e.hasMoreElements()) {
			String paramname = e.nextElement().toString();

			if (paramname.startsWith("contactgroups")) {
				Long id = Long.valueOf(paramname.replace("contactgroups", ""));
				contactgroups.add(id);
			}
		}

		// Initialisation of the contact
		boolean isCompany = false;
		if (!nsiret.isEmpty()) {
			isCompany = true;
		}

		ServletContext ctx = getServletContext();
		
		if (isCompany) {
			Entreprise entity = new Entreprise();
			
			entity.setFirstName(fn);
			entity.setLastName(ln);
			entity.setEmail(em);
			entity.setNumSiret(Integer.valueOf(nsiret));			

			// On configure une nouvelle adresse pour la requete HQL par
			// l'exemple
			Address add = new Address(st, city, zip, count);
			entity.setAdd(add);
			for (PhoneNumber p : createPhones(home, mob, work)) {
				entity.addPhone(p);
			}

			IDAOContactGroup DAOCG = DAOFactory.getDAOContactGroup(ctx);
			for (Long id : contactgroups) {
				ContactGroup cg = DAOCG.find(id);
				entity.addBooks(cg);
			}
			 
			IDAOEntreprise DAOE = DAOFactory.getDAOEntreprise(ctx);
			DAOE.create(entity);
		}
		else 
		{
			Contact entity = new Contact();
			entity.setFirstName(fn);
			entity.setLastName(ln);
			entity.setEmail(em);

			// On configure une nouvelle adresse pour la requete HQL par
			// l'exemple
			Address add = new Address(st, city, zip, count);
			entity.setAdd(add);
			for (PhoneNumber p : createPhones(home, mob, work)) {
				entity.addPhone(p);
			}

			IDAOContactGroup DAOCG = DAOFactory.getDAOContactGroup(ctx);
			for (Long id : contactgroups) {
				ContactGroup cg = DAOCG.find(id);
				entity.addBooks(cg);
			}
			
			IDAOContact DAOC = DAOFactory.getDAOContact(ctx);
			DAOC.create((Contact) entity);
		}

		response.sendRedirect("LoadAllContacts");
	}

	public Set<PhoneNumber> createPhones(String home, String mobile, String work) {
		Set<PhoneNumber> setRes = new HashSet<PhoneNumber>();
		home = home.replaceAll("\\s", "");
		if (home != "") {
			PhoneNumber p = new PhoneNumber();
			p.setPhoneKind("Home");
			p.setPhoneNumber(home);
			setRes.add(p);
			System.out.println("home");
		}

		mobile = mobile.replaceAll("\\s", "");
		if (mobile != "") {
			PhoneNumber p = new PhoneNumber();
			p.setPhoneKind("Mobile");
			p.setPhoneNumber(mobile);
			setRes.add(p);
			System.out.println("mobile");
		}

		work = work.replaceAll("\\s", "");
		if (work != "") {
			PhoneNumber p = new PhoneNumber();
			p.setPhoneKind("Work");
			p.setPhoneNumber(work);
			setRes.add(p);
			System.out.println("work");
		}

		return setRes;
	}

}
